package com.cardone.persistent.builder;

import org.apache.commons.collections.*;
import org.apache.commons.lang3.*;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 映射生成器工具
 *
 * @author yaohaitao
 */
public class ModelUtils {
    /**
     * 实例化对象映射
     *
     * @param attrs 属性集合
     * @return 对象映射实例
     */
    public static Model newModel(final Map<String, Object> attrs, final ModelArgs... modelArgss) {
        final Model model = ModelUtils.newModel(modelArgss);

        if (MapUtils.isNotEmpty(attrs)) {
            model.putAll(attrs);
        }

        return model;
    }

    /**
     * 实例化对象映射
     *
     * @param modelArgss 对象参数
     * @return 对象映射实例
     */
    public static Model newModel(final ModelArgs... modelArgss) {
        return ModelUtils.put(new ModelDefault(), modelArgss);
    }

    /**
     * 填充
     *
     * @param model      对象映射
     * @param modelArgss 对象参数
     */
    public static Model put(final Model model, final ModelArgs... modelArgss) {
        if (org.apache.commons.lang3.ArrayUtils.isEmpty(modelArgss)) {
            return model;
        }

        for (final ModelArgs modelArgs : modelArgss) {
            if (modelArgs == null) {
                continue;
            }

            if (ArrayUtils.isNotEmpty(modelArgs.getKeyBases())) {
                model.putExtend(modelArgs.getKeyPrefix(), modelArgs.getKeyBases(), modelArgs.getKeySuffix(), modelArgs.getValue());
            }

            if (!CollectionUtils.isEmpty(modelArgs.getKvMap())) {
                if (ArrayUtils.isEmpty(modelArgs.getUseProperties())) {
                    model.putExtend(modelArgs.getKeyPrefix(), modelArgs.getKvMap(), modelArgs.getKeySuffix());
                } else {
                    for (String usePropertie : modelArgs.getUseProperties()) {
                        model.putExtend(modelArgs.getKeyPrefix(), usePropertie, modelArgs.getKeySuffix(), modelArgs.getKvMap().get(usePropertie));
                    }
                }
            }

            if ((modelArgs.getO() != null) || (modelArgs.getC() != null)) {
                model.putObjectField(modelArgs);
            }
        }

        return model;
    }

    /**
     * 填充
     *
     * @param model     对象映射
     * @param modelMaps 对象参数
     */
    public static Model put(final Model model, final Map<String, Object>... modelMaps) {
        if (ArrayUtils.isEmpty(modelMaps)) {
            return model;
        }

        for (Map<String, Object> modelMap : modelMaps) {
            if (MapUtils.isNotEmpty(modelMap)) {
                model.putAll(modelMap);
            }
        }

        return model;
    }
}
